package com.lcb.redison;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/****
 * @Author:刘长柏
 * @Date: 2021-01-20 11:01
 * @Description:分布式锁测试
 *****/
@RestController
public class RedissonController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Redisson redisson;


    @RequestMapping("/redissonDeductStock")
    public String redissonDeductStock() {
        //锁续命,开启子线程,在超时时间1/3处世,添加超时时间
        String lockKey = "lockKey";
        String clientId = UUID.randomUUID().toString();
        RLock lock = redisson.getLock(lockKey);

        try {
            //加锁 实现锁续命,默认30秒
            lock.lock();
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                int realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("stock", realStock + "");
                System.out.println("扣减成功,库存剩余:" + realStock);
            } else {
                System.out.println("扣减失败,库存不足!");
            }
        } finally {
            lock.unlock();
        }
        return "end";
    }

    @RequestMapping("/deductStock")
    public String deductStock() {
        //锁续命,开启子线程,在超时时间1/3处世,添加超时时间
        String lockKey = "lockKey";
        String clientId = UUID.randomUUID().toString();
        try {
            //Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "lcb");
            //stringRedisTemplate.expire(lockKey, 10, TimeUnit.SECONDS);

            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 30, TimeUnit.SECONDS);

            if (!result) {
                return "error";
            }

            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                int realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("stock", realStock + "");

                System.out.println("扣减成功,库存剩余:" + realStock);
            } else {
                System.out.println("扣减失败,库存不足!");
            }
        } finally {
            if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
                stringRedisTemplate.delete(lockKey);
            }
        }

        return "end";
    }
}
